/*
 * 文件名：ApnsUtil.java
 * 版权：
 * 描述：apple推送工具类
 * 修改人：zuo liubo
 * 修改时间：2012-12-22 下午8:21:45
 */
package com.scpii.api.service.push.apns;

import javapns.notification.PushNotificationPayload;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.jackson.map.ObjectMapper;

import com.scpii.api.common.exception.IOSTokenFormatException;
import com.scpii.api.domain.push.Message;

/**
 * @description apple推送工具类
 * @author zuo liubo
 * @date 2012-12-22
 */
public class ApnsUtil {

	private static Log logger = LogFactory.getLog(ApnsUtil.class);

	private static ObjectMapper objectMapper;

	/**
	 * 封装向APNS推送的消息体
	 * 
	 * @param message
	 * @return
	 */
	public static String encapsulationMsg(Message message) {
		try {
			objectMapper = new ObjectMapper();
			AppleMessage appleMessage = new AppleMessage();
			String summary = message.getSummary();
			// 处理数据 ,发送给APNS的消息体的字节数最大值为256
			byte[] b = summary.getBytes();
			if (b.length > 180) {
				summary = new String(b, 0, 180);
				summary = summary.substring(0, summary.length() - 1);
			}
			appleMessage.getAps().setAlert(summary);
			appleMessage.getAps().setMessageId(message.getMessageId());
			return objectMapper.writeValueAsString(appleMessage);
		} catch (Exception e) {
			logger.error(e);
			return null;
		}
	}

	
	public static PushNotificationPayload getPayload(String message) {
		return getPayload(message, 1);
	}
	
	/**
	 * 根据message获取Payload
	 * @param message	消息主题
	 * @param badge	标记数，即ICON上面的小数字
	 * @return
	 */
	public static PushNotificationPayload getPayload(String message,int badge) {
		PushNotificationPayload payload = null;
		try {
			payload = PushNotificationPayload.fromJSON(message);
			payload.addBadge(badge); // 图标小红圈的数值
			payload.addSound("default"); // 铃音 默认
		} catch (Exception e) {
			logger.equals(e);
		}
		return payload;
	}

	/**
	 * 校验IOS_TOKEN</br>
	 * 校验规则为：iosToken不能为null，并且必须为64位字符串
	 * @param iosToken
	 */
	public static void validateIOSToken(String iosToken) {
		if (iosToken == null || iosToken.length() != 64) {
			throw new IOSTokenFormatException();
		}
	}
}
